package test.search;

import java.io.IOException;

import lucene.Lucenes;
import lucene.Searcher;
import luceneUtil.AnalyzerUtils;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.spans.SpanFirstQuery;
import org.apache.lucene.search.spans.SpanQuery;
import org.apache.lucene.search.spans.SpanTermQuery;
import org.apache.lucene.search.spans.Spans;
import org.apache.lucene.util.AttributeSource;

public class SearchSpanQuery {
	static IndexReader reader = null;
	static {
		try {
			reader = IndexReader.open(Lucenes.getFSDirectory("E:\\index"));
		} catch (CorruptIndexException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	static Searcher searcher = new Searcher();

	public static void main(String[] args) throws IOException {
		test();
		test2();
	}

	private static void test2() throws IOException {
		SpanTermQuery spanTermQuery = new SpanTermQuery(new Term("title2",
				"love"));
		SpanFirstQuery spanFirstQuery = new SpanFirstQuery(spanTermQuery, 5);
		dumpSpans(spanFirstQuery);
	}

	private static void test() throws IOException {
		SpanTermQuery spanTermQuery = new SpanTermQuery(new Term("title2",
				"love"));
		dumpSpans(spanTermQuery);
	}

	private static void dumpSpans(SpanQuery query) throws IOException {
		Analyzer analyzer = Lucenes.getStandardAnalyzer();
		Spans spans = query.getSpans(reader);
		System.out.println(query + ":");
		int numSpans = 0;
		TopDocs hits = searcher.executeQuery(query, 10);
		float[] scores = new float[100];
		for (int i = 0; i < hits.scoreDocs.length; i++) {
			scores[hits.scoreDocs[i].doc] = hits.scoreDocs[i].score;
		}
		while (spans.next()) {
			numSpans++;
			int id = spans.doc();

			Document doc = reader.document(id);
			System.out.println(doc.get("title"));
			// for simplicity - assume tokens are in sequential,
			// positions, starting from 0
			AttributeSource[] tokens = AnalyzerUtils.tokensFromAnalysis(
					analyzer, doc.get("title2"));
			StringBuffer buffer = new StringBuffer();
			buffer.append(" ");
			for (int i = 0; i < tokens.length; i++) {
				if (i == spans.start()) {
					buffer.append("<");
				}
				buffer.append(AnalyzerUtils.getTerm(tokens[i]));
				if (i + 1 == spans.end()) {
					buffer.append(">");
				}
				buffer.append(" ");
			}
			buffer.append("(" + scores[id] + ") ");
			System.out.println(buffer);
			// System.out.println(searcher.explain(query, id));
		}
		if (numSpans == 0) {
			System.out.println(" No spans");
		}
		System.out.println();
	}
}
